package com.sc.nft.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sc.nft.dao.MallBannerDao;
import com.sc.nft.entity.MallBanner;
import com.sc.nft.entity.vo.MallBannerVO;
import com.sc.nft.enums.RedisKeyEnum;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.MallBannerService;
import com.sc.nft.sup.PageRequest;
import com.sc.nft.util.RedisUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 商城banner表(MallBanner)表服务实现类
 *
 * @author wwc
 * @since 2023-05-16 10:58:42
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class MallBannerServiceImpl implements MallBannerService {

    private final MallBannerDao mallBannerDao;
    private final RedisUtil redisUtil;
    /**
     * 根据id获取数据
     *
     * @param id
     * @return
     */
    @Override
    public MallBanner getByIdAndStatus(Long id, Integer status) {
        return mallBannerDao.getByIdAndStatus(id, status);
    }

    /**
     * 获取列表
     *
     * @return
     */
    @Override
    public List<MallBannerVO> list(Long location, Integer status) {
//        return mallBannerDao.listByLocationAndStatus(location,status);
        return mallBannerDao.listByLocationAndStatusAndTime(location,status, DateUtil.date());
    }

    /**
     * 分页获取列表
     *
     * @param pageRequest
     * @return
     */
    @Override
    public Page<MallBannerVO> page(PageRequest pageRequest) {
        return mallBannerDao.pageAdmin(pageRequest);
    }

    /**
     * 根据id删除数据
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Long id) {
        mallBannerDao.removeById(id);
        redisUtil.del(RedisKeyEnum.HOME_BANNER.getKey());
    }

    /**
     * 根据id更新数据
     *
     * @param mallBanner
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(MallBanner mallBanner) {
        MallBanner byId = mallBannerDao.getById(mallBanner.getId());
        if (mallBanner.getStatus()==null) {
            if (byId.getStatus()){
                throw new GlobalRunTimeException("已上架的banner不能修改");
            }
        }
        mallBanner.updateById();
        redisUtil.del(RedisKeyEnum.HOME_BANNER.getKey());
    }

    @Override
    public void updateStatus(Long id, Boolean status) {
        MallBanner mallBanner = new MallBanner();
        mallBanner.setStatus(status);
        mallBanner.setId(id);
        mallBannerDao.updateById(mallBanner);
    }

    /**
     * 新增数据
     *
     * @param mallBanner
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(MallBanner mallBanner) {
        mallBanner.insert();
        redisUtil.del(RedisKeyEnum.HOME_BANNER.getKey());
    }

}
